/**
 * 模拟原生路由
 */

const Koa = require('koa');

const fs = require('fs');

const path = require('path');

const app = new Koa();

/**
 * 
 * @param {*} url page文件夹下面的html页面
 */
function readContent(url) {
  return new Promise((resolve, reject) => {
    const pageUrl = path.join(__dirname, `page/${url}`);
    fs.readFile(pageUrl, 'binary', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    })
  })
}

/**
 * 
 * @param {*} params 通过ctx.request.url获取的路由
 */
async function renderHtml(params) {
  let page = '404.html';
  switch (params) {
    case '/':
      page = 'index.html';
      break;
    case '/index':
      page = 'index.html';
      break;
    case '/cs':
      page = 'cs.html'
      break;
    default:
      break;
  }
  return await readContent(page);
}

app.use(async ctx => {
  const requestUrl = ctx.request.url;
  const html = await renderHtml(requestUrl);
  ctx.body = html;
})

app.listen(3030, () => {
  console.log('3030 router');
})